//
//  NHBaseRequest.m
//  LZNeiHan
//
//  Created by 梁梓烽 on 16/10/2.
//  Copyright © 2016年 liangzifeng. All rights reserved.
//

#import "NHBaseRequest.h"
#import "NHRequestManager.h"

@implementation NHBaseRequest

#pragma mark -属性的set get方法
-(void)setUrl:(NSString *)url
{
    //url属性set方法的容错处理
    if (url.length == 0|| [url isKindOfClass:[NSNull class]]) {
        return ;
    }
    _url = url;

}
#pragma mark -快速构造方法
-(instancetype)nh_request
{
  return   [self nh_requestWith:nil ];
}

-(instancetype)nh_requestWith:(NSString *)url
{
    return [self nh_requestWith:url FinishHandle:nil];
}

-(instancetype)nh_requestWith:(NSString *)url  FinishHandle:(NHBaseRequestFinishHandle)handle
{
    if (self == [super init]) {
        self.url = url;
    }
    
    return self;
}


#pragma mark -请求接口
-(void)nh_sendRequest
{
    [self nh_sendRequestWithComplemation:nil];
}

-(void)nh_sendRequestWithComplemation:(NHBaseRequestFinishHandle)handle
{
    if (self.is_Post) {
        // post
  
        [NHRequestManager Post:self.url params:[self params] responseSerializerType:NHResponseSeializerTypeDefault success:^(id response) {
              [self handleResponse:response handle:handle];
        } failure:^(NSError * error) {
            
        }];
    
    }
    
    else
    {
        //get
        [NHRequestManager Get:self.url params:[self params] responseSerializerType:NHResponseSeializerTypeDefault success:^(id response) {
            
             [self handleResponse:response handle:handle];
        } failure:^(NSError * error) {
            
        }];
        
    }
}


#pragma mark -其他
-(void)handleResponse:(id)response handle:(NHBaseRequestFinishHandle)handle
{
    
    BOOL success = [response[@"success"] isEqualToString:@"success"];
    if (!success) {
        //重新发送请求
        if (response[@"retry"]) {
            [self nh_sendRequestWithComplemation:handle];
        }
    }
    else
    {   //sucess为yes 请求成功
        if (handle) {
            handle(success,response,@"");
        }
        else
        {
            if ([self.deleage respondsToSelector:@selector(BaseRequestFinishRequest:response:message:)]) {
                [self.deleage BaseRequestFinishRequest:success response:response message:@""];
            }
        }
        
    }
}


-(NSMutableDictionary *)params
{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    
    
    return dic;
}



@end
